/* -------------------------------------------------------------------
 * BIE is Copyright 2001-2002 Brunswick Corp.
 * -------------------------------------------------------------------
 * Please read the legal notices (docs/legal.txt) and the license
 * (docs/license.txt) that came with this distribution before using
 * this software.
 * -------------------------------------------------------------------
 */

/** 
 * This class simply takes a file and a client name.
 *
 * If there is no match, System.exit(0). 
 * Else if there is a match, System.exit(-1).
 * Presumably, failure indicates
 * that the given file has target client name.
 *
 * MatchClient.java
 *
 * Created on March 12, 2003, 12:25 PM
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.NullPointerException;
import java.io.Reader;
import java.util.regex.Pattern;

/**
 *
 * @author  MLee
 */
public class MatchClient {

    public static void main (String [] args) throws IOException{
        if ( args.length < 2 ) {
            throw new IllegalArgumentException
            ("Usage: MatchClient <targetFileName> <clientName>");
        }
        String fileName = args[0];
        String clientName = args[1];
        String clientNameRegexp = ".*<client name=\"" + clientName + "\">.*";
        File targetFile = new File(fileName);
        boolean hasClient = false;
        
        //First make sure that the exists
        if(!targetFile.exists()){
            abort("MatchClient: Target file does not exist.");
        }
        if(!targetFile.canRead()){
            abort("MatchClient: Cannot read file.");
        }
              
        BufferedReader br = new BufferedReader( new FileReader( fileName ) );
        String line;
        while( (line = br.readLine()) != null ) {
            if ( hasClient = Pattern.matches(clientNameRegexp,line) ) {
                break;   
            }               
        }
        //if no match, sucessful exit code else
        //failure code
        System.out.println ("MatchClient: " + hasClient);
        if (!hasClient){
            System.exit(0);
        } else {
            System.exit(-1);
        }
    }
    
    private static void abort (String msg) throws IOException{
        throw new IOException(msg);        
    }
}
